<template>
  <el-dialog
    :visible="visible"
    @close="handleClose"
    :title="$t('developer.company_developer_import')"
    width="550px"
  >
    <el-upload
      class="developer-upload"
      ref="upload"
      action
      :headers="myHeader"
      :http-request="handleUploadFile"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="1"
      drag
      accept=".xls,.xlsx"
      style="text-align: center"
      :auto-upload="false"
    >
      <!-- TODO: -->
      <template #tip>
        <div style="width: 360px; align: center">
          <svg-icon icon-class="Upload" />
          <div class="el-upload__text">
            {{ $t("developer.upload_drag_tip") }}
            <em>{{ $t("developer.click_upload") }}</em>
          </div>

          <div class="el-upload__tip" style="word-break: break-word">
            {{ $t("developer.excel_upload_tip_excel_max_1000") }}
          </div>
          >
        </div>
      </template>
    </el-upload>
    <div style="text-align: center">
      <el-button
        type="text"
        icon="el-icon-download"
        style="text-decoration: underline"
        @click="downloadCompanyTemplateExcel"
        >{{ $t("developer.download_excel_template_company") }}
      </el-button>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button text @click="handleClose">{{ $t("page.cancel") }}</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploadLoading">{{
          $t("page.confirm")
        }}</el-button>
      </span></template
    >
  </el-dialog>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import { addCompanyDeveloperByFile } from "@/api";

export default {
  props: {
    visible: Boolean,
  },
  data() {
    return {
      uploadLoading: false,
      companyDeveloperUploadUrl: "",
      fileList: [],
      myHeader: {
        "WEB-TOKEN": getToken(),
        LANG: localStorage.getItem(this.$store.state.user.keys.storage.lang) || "en-US",
      },
    };
  },
  methods: {
    init() {
      this.companyDeveloperUploadUrl =
        import.meta.env.VITE_APP_BASE_API +
        "/online/developer-admin/developer/import-company-developer";
    },
    handleUploadFile() {
      const formdata = new FormData();
      formdata.append("file", this.fileList[0].raw);
      addCompanyDeveloperByFile(formdata)
        .then((res) => {
          this.uploadLoading = false;
          this.$message.success(this.$t("common.operate_success"));
          this.$emit("close");
          this.fileList = [];
          this.$emit("refreshDataList");
        })
        .catch((e) => {
          this.uploadLoading = false;
          this.$confirmError(e);
        })
        .finally(() => {
          this.uploadLoading = false;
        });
    },
    handleClose() {
      this.$emit("close");
      this.fileList = [];
      this.$emit("refreshDataList");
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    // 下载模板
    downLoad(url, fileName) {
      axios({
        method: "get",
        url: url,
        responseType: "blob",
        headers: this.myHeader,
      })
        .then(({ data }) => {
          if (data) {
            var url = window.URL.createObjectURL(data);
            var a = document.createElement("a");
            a.href = url;
            a.download = fileName;
            a.click();
          } else {
            this.$message.error(this.$t("developer.download_excel_error"));
          }
        })
        .catch(this.$confirmError);
    },
    downloadCompanyTemplateExcel() {
      this.downLoad(
        import.meta.env.VITE_APP_BASE_API +
          "/online/developer-admin/developer/export-company-template",
        "Company-developer-import-template.xlsx"
      );
    },
    handleBeforeUpload(file) {
      var fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = fileType === "xls";
      const extension2 = fileType === "xlsx";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!extension && !extension2) {
        this.$message.warning(this.$t("developer.upload_file_tip_xls_xlsx"));
        return false;
      }
      if (!isLt5M) {
        this.$message.warning(this.$t("developer.file_size_5MB_limit"));
        return false;
      }
      return (extension || extension2) && isLt5M;
    },
    handleSuccess(data, file, fileList) {
      this.uploadLoading = false;
      if (data.code === "0000") {
        this.$emit("close");
        this.fileList = [];
      } else {
        this.$message.error(this.$t("developer.import_excel_error"));
      }
      this.fileList = [];
    },
    handleError(err, file, fileList) {
      this.uploadLoading = false;
      const errMsg = JSON.parse(err.message);
      this.$message.error(this.$t("developer.import_excel_error") + ":" + errMsg.message);
    },
    // 上传的文件个数超出设定时触发的函数
    handleExceed(files, fileList) {
      this.$message({
        type: "info",
        message: this.$t("developer.msg_upload_limit_quantity"),
        duration: 6000,
      });
    },
    submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning(this.$t("developer.upload_file_tip"));
        return;
      }
      this.uploadLoading = true;
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  height: 86px;
}
</style>
